package com.jlwl.houseservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlwl.houseservice.entity.Employee;
import com.jlwl.houseservice.entity.Order;
import com.jlwl.houseservice.entity.Review;
import com.jlwl.houseservice.entity.Service;
import com.jlwl.houseservice.mapper.ReviewMapper;
import com.jlwl.houseservice.service.EmployeeService;
import com.jlwl.houseservice.service.OrderService;
import com.jlwl.houseservice.service.ReviewService;
import com.jlwl.houseservice.service.ServiceService;
import com.jlwl.houseservice.vo.ReviewCreateVO;
import com.jlwl.houseservice.vo.ReviewQueryVO;
import com.jlwl.houseservice.vo.ReviewReplyVO;
import com.jlwl.houseservice.vo.ReviewStatsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评价Service实现类
 */
@Component
@org.springframework.stereotype.Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ServiceService serviceService;

    @Autowired
    private EmployeeService employeeService;

    @Override
    public Page<Review> pageList(ReviewQueryVO queryVO) {
        LambdaQueryWrapper<Review> queryWrapper = new LambdaQueryWrapper<>();
        
        // 服务ID筛选
        if (queryVO.getServiceId() != null) {
            queryWrapper.eq(Review::getServiceId, queryVO.getServiceId());
        }
        
        // 员工ID筛选
        if (queryVO.getEmployeeId() != null) {
            queryWrapper.eq(Review::getEmployeeId, queryVO.getEmployeeId());
        }
        
        // 用户ID筛选
        if (queryVO.getUserId() != null) {
            queryWrapper.eq(Review::getUserId, queryVO.getUserId());
        }
        
        // 订单编号筛选
        if (StringUtils.hasText(queryVO.getOrderNo())) {
            queryWrapper.eq(Review::getOrderNo, queryVO.getOrderNo());
        }
        
        // 评分筛选
        if (queryVO.getRating() != null) {
            queryWrapper.eq(Review::getRating, queryVO.getRating());
        }
        
        // 是否有图片筛选
        if (queryVO.getHasImage() != null && queryVO.getHasImage()) {
            queryWrapper.isNotNull(Review::getImages)
                    .ne(Review::getImages, "");
        }
        
        // 状态筛选
        if (queryVO.getStatus() != null) {
            queryWrapper.eq(Review::getStatus, queryVO.getStatus());
        } else {
            // 默认只查询显示的评价
            queryWrapper.eq(Review::getStatus, 1);
        }
        
        // 默认按创建时间倒序排序
        queryWrapper.orderByDesc(Review::getCreatedAt);
        
        // 分页查询
        return page(new Page<>(queryVO.getPage(), queryVO.getSize()), queryWrapper);
    }

    @Override
    @Transactional
    public boolean createReview(ReviewCreateVO createVO, Integer userId) {
        // 检查是否已评价
        if (hasReviewed(createVO.getOrderNo(), userId)) {
            return false;
        }
        
        // 获取订单信息
        Order order = orderService.getOrderByOrderNo(createVO.getOrderNo());
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 创建评价
        Review review = new Review();
        review.setOrderNo(createVO.getOrderNo());
        review.setUserId(userId);
        review.setServiceId(order.getServiceId());
        review.setEmployeeId(order.getEmployeeId());
        review.setRating(createVO.getRating());
        review.setContent(createVO.getContent());
        
        // 处理标签
        if (createVO.getTags() != null && !createVO.getTags().isEmpty()) {
            review.setTags(String.join(",", createVO.getTags()));
        }
        
        // 处理图片
        if (createVO.getImages() != null && !createVO.getImages().isEmpty()) {
            review.setImages(String.join(",", createVO.getImages()));
        }
        
        review.setStatus(1); // 默认显示
        review.setCreatedAt(LocalDateTime.now());
        review.setUpdatedAt(LocalDateTime.now());
        
        boolean success = save(review);
        
        if (success) {
            // 更新服务评分
            updateServiceRating(order.getServiceId());
            
            // 更新员工评分
            if (order.getEmployeeId() != null) {
                employeeService.updateEmployeeRating(order.getEmployeeId(), (double) createVO.getRating());
            }
        }
        
        return success;
    }

    @Override
    @Transactional
    public boolean replyReview(Integer id, ReviewReplyVO replyVO) {
        Review review = getById(id);
        if (review == null) {
            return false;
        }
        
        return update(new LambdaUpdateWrapper<Review>()
                .eq(Review::getId, id)
                .set(Review::getReply, replyVO.getReply())
                .set(Review::getReplyTime, LocalDateTime.now())
                .set(Review::getUpdatedAt, LocalDateTime.now()));
    }

    @Override
    @Transactional
    public boolean updateReviewStatus(Integer id, Integer status) {
        Review review = getById(id);
        if (review == null) {
            return false;
        }
        
        boolean success = update(new LambdaUpdateWrapper<Review>()
                .eq(Review::getId, id)
                .set(Review::getStatus, status)
                .set(Review::getUpdatedAt, LocalDateTime.now()));
        
        if (success) {
            // 更新服务评分
            updateServiceRating(review.getServiceId());
            
            // 更新员工评分
            if (review.getEmployeeId() != null) {
                updateEmployeeRating(review.getEmployeeId());
            }
        }
        
        return success;
    }

    @Override
    public ReviewStatsVO getServiceReviewStats(Integer serviceId) {
        // 获取评分统计
        Map<String, Object> ratingStats = baseMapper.getServiceRatingStats(serviceId);
        
        // 获取标签统计
        List<Map<String, Object>> tagStats = baseMapper.getServiceTagStats(serviceId);
        
        // 构建返回结果
        ReviewStatsVO statsVO = new ReviewStatsVO();
        
        if (ratingStats != null) {
            statsVO.setTotalCount(((Number) ratingStats.get("total")).intValue());
            
            Object avgRating = ratingStats.get("avgRating");
            if (avgRating != null) {
                statsVO.setAvgRating(new BigDecimal(avgRating.toString()));
            } else {
                statsVO.setAvgRating(BigDecimal.ZERO);
            }
            
            // 评分分布
            Map<String, Integer> ratingDistribution = new HashMap<>();
            ratingDistribution.put("5", ((Number) ratingStats.getOrDefault("rating5", 0)).intValue());
            ratingDistribution.put("4", ((Number) ratingStats.getOrDefault("rating4", 0)).intValue());
            ratingDistribution.put("3", ((Number) ratingStats.getOrDefault("rating3", 0)).intValue());
            ratingDistribution.put("2", ((Number) ratingStats.getOrDefault("rating2", 0)).intValue());
            ratingDistribution.put("1", ((Number) ratingStats.getOrDefault("rating1", 0)).intValue());
            
            statsVO.setRatingDistribution(ratingDistribution);
        } else {
            statsVO.setTotalCount(0);
            statsVO.setAvgRating(BigDecimal.ZERO);
            statsVO.setRatingDistribution(new HashMap<>());
        }
        
        statsVO.setTagStats(tagStats);
        
        return statsVO;
    }

    @Override
    public ReviewStatsVO getEmployeeReviewStats(Integer employeeId) {
        // 获取评分统计
        Map<String, Object> ratingStats = baseMapper.getEmployeeRatingStats(employeeId);
        
        // 构建返回结果
        ReviewStatsVO statsVO = new ReviewStatsVO();
        
        if (ratingStats != null) {
            statsVO.setTotalCount(((Number) ratingStats.get("total")).intValue());
            
            Object avgRating = ratingStats.get("avgRating");
            if (avgRating != null) {
                statsVO.setAvgRating(new BigDecimal(avgRating.toString()));
            } else {
                statsVO.setAvgRating(BigDecimal.ZERO);
            }
            
            // 评分分布
            Map<String, Integer> ratingDistribution = new HashMap<>();
            ratingDistribution.put("5", ((Number) ratingStats.getOrDefault("rating5", 0)).intValue());
            ratingDistribution.put("4", ((Number) ratingStats.getOrDefault("rating4", 0)).intValue());
            ratingDistribution.put("3", ((Number) ratingStats.getOrDefault("rating3", 0)).intValue());
            ratingDistribution.put("2", ((Number) ratingStats.getOrDefault("rating2", 0)).intValue());
            ratingDistribution.put("1", ((Number) ratingStats.getOrDefault("rating1", 0)).intValue());
            
            statsVO.setRatingDistribution(ratingDistribution);
        } else {
            statsVO.setTotalCount(0);
            statsVO.setAvgRating(BigDecimal.ZERO);
            statsVO.setRatingDistribution(new HashMap<>());
        }
        
        return statsVO;
    }

    @Override
    public Page<Review> getUserReviews(Integer userId, Integer page, Integer size) {
        return page(new Page<>(page, size), new LambdaQueryWrapper<Review>()
                .eq(Review::getUserId, userId)
                .eq(Review::getStatus, 1)
                .orderByDesc(Review::getCreatedAt));
    }

    @Override
    public boolean hasReviewed(String orderNo, Integer userId) {
        return count(new LambdaQueryWrapper<Review>()
                .eq(Review::getOrderNo, orderNo)
                .eq(Review::getUserId, userId)) > 0;
    }
    
    /**
     * 更新服务评分
     */
    private void updateServiceRating(Integer serviceId) {
        // 获取评分统计
        Map<String, Object> ratingStats = baseMapper.getServiceRatingStats(serviceId);
        
        if (ratingStats != null && ratingStats.get("avgRating") != null) {
            BigDecimal avgRating = new BigDecimal(ratingStats.get("avgRating").toString());
            
            // 更新服务评分
            serviceService.updateServiceRating(serviceId, avgRating);
        }
    }
    
    /**
     * 更新员工评分
     */
    private void updateEmployeeRating(Integer employeeId) {
        // 获取评分统计
        Map<String, Object> ratingStats = baseMapper.getEmployeeRatingStats(employeeId);
        
        if (ratingStats != null && ratingStats.get("avgRating") != null) {
            Double avgRating = Double.parseDouble(ratingStats.get("avgRating").toString());
            
            // 更新员工评分
            employeeService.updateEmployeeRating(employeeId, avgRating);
        }
    }
} 